/*

 wing_db.js for database operating

 2011.11.19. #320 #321 create， function create,get
 2012.2.25. re-build begin
 

 */

function _kv() {
	this.length = 0;
	this.items = new Array();
	for(var i = 0; i < arguments.length; i += 2) {
		if( typeof (arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}

	this.remove = function(in_key) {
		var tmp_previous;
		if( typeof (this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_previous = this.items[in_key];
			delete this.items[in_key];
		}

		return tmp_previous;
	}

	this.get = function(in_key) {
		return this.items[in_key];
	}

	this.set = function(in_key, in_value) {
		var tmp_previous;
		if( typeof (in_value) != 'undefined') {
			if( typeof (this.items[in_key]) == 'undefined') {
				this.length++;
			} else {
				tmp_previous = this.items[in_key];
			}

			this.items[in_key] = in_value;
		}

		return tmp_previous;
	}

	this.has= function(in_key) {
		return typeof (this.items[in_key]) != 'undefined';
	}

	this.clear = function() {
		for(var i in this.items) {
			delete this.items[i];
		}

		this.length = 0;
	}
}

function _save_kv(lkv,lfilename){
	//serialize
	var myObjectString = JSON.stringify(lkv);
	Ti.API.info(myObjectString);

	var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, lfilename);
	f.write(myObjectString);
	Ti.API.info('write kv json to file');
}

function _load_kv(lfilename){
	var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, lfilename);
	var contents = f.read();
	Ti.API.info('read:' + contents);

	//deserialize...
	var lkv0 = JSON.parse(contents);
	
	var lkv = new _kv();
		
	_.extend(lkv,lkv0);
	
	return lkv;
}
